package org.dyndns.ipignoli.droidcruise.recording;

import org.dyndns.ipignoli.droidcruise.position.MyCoordinate;


public class RouteRecording extends Recording{

  protected static String getDefaultLocality(double firstLatitude,
      double firstLongitude, double lastLatitude, double lastLongitude){
    return new StringBuffer(Recording.getDefaultLocality(firstLatitude,
        firstLongitude)).append("-")
        .append(Recording.getDefaultLocality(lastLatitude, lastLongitude))
        .toString();
  }

  private double lastLatitude;
  private double lastLongitude;

  public RouteRecording(long _id, MyCoordinate firstLocation,
      MyCoordinate lastLocation, int limit, String comment, boolean sent){
    this(_id, firstLocation.getTime(), getDefaultLocality(
        firstLocation.getLatitude(), firstLocation.getLongitude(),
        lastLocation.getLatitude(), lastLocation.getLongitude()), false,
        firstLocation.getLatitude(), firstLocation.getLongitude(), lastLocation
            .getLatitude(), lastLocation.getLongitude(), limit, comment, sent);
  }

  public RouteRecording(long _id, long date, String locality,
      boolean localityOK, double firstLatitude, double firstLongitude,
      double lastLatitude, double lastLongitude, int limit, String comment,
      boolean sent){
    super(_id, Recording.ROUTE_TYPE, date, locality, localityOK, firstLatitude,
        firstLongitude, limit, comment, sent);
    setLastLatitude(lastLatitude);
    setLastLongitude(lastLongitude);
    setLocality(locality, localityOK);
  }

  @Override
  public void setLocality(String locality, boolean localityOK){
    if(localityOK){
      setLocality(locality);
      setLocalityOK(localityOK);
      return;
    }

    try{
      String l1 = geocoder.getFromLocation(getLatitude(), getLongitude());
      String l2 =
          geocoder.getFromLocation(getLastLatitude(), getLastLongitude());
      if(l1 == null || l2 == null)
        throw new Exception();
      setLocality(new StringBuffer(l1).append("-").append(l2).toString());
      setLocalityOK(true);
    }catch(Exception e){
      setLocality(locality);
      setLocalityOK(false);
    }
  }

  public double getLastLatitude(){
    return lastLatitude;
  }

  public void setLastLatitude(double latitude){
    lastLatitude = latitude;
  }

  public double getLastLongitude(){
    return lastLongitude;
  }

  public void setLastLongitude(double longitude){
    lastLongitude = longitude;
  }
}
